package com.loy;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.loy.entity.HelloProto;
import com.loy.entity.HelloServiceGrpc;
import com.loy.entity.TestProto;
import com.loy.entity.TestServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.netty.shaded.io.netty.util.concurrent.Future;
import io.grpc.stub.StreamObserver;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 6. 双向rpc
 */
public class GrpcClient7 {

    public static void main(String[] args) {
        // 1. 创建和服务器端进行通信的管道
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext().build();

        try{

            TestServiceGrpc.TestServiceFutureStub testServiceFutureStub = TestServiceGrpc.newFutureStub(managedChannel);
            ListenableFuture<TestProto.TestResponse> testResponseListenableFuture = testServiceFutureStub.testSuns(
                    TestProto.TestRequest.newBuilder().setName("xjr").build());

            // 获取响应结果
            /**
             * 1. 同步处理
             * */
            //TestProto.TestResponse response = testResponseListenableFuture.get();
            //System.out.println(response.getResult());// 只要服务器端不响应，那么客户端会一直在这里阻塞
            //System.out.println("后续操作.....................");

            /**
             * 2. 异步处理
             *  这个操作只能知道服务器端响应回来了，但是不能获取服务器响应回来的数据，
             */
            //testResponseListenableFuture.addListener(()->{
            //    System.out.println("异步的rpc响应回来了.................");
            //}, Executors.newCachedThreadPool());
            //System.out.println("后续操作.....................");

            /**
             * 3. 异步处理，并获取服务器端响应回来的数据
             */
            Futures.addCallback(testResponseListenableFuture, new FutureCallback<TestProto.TestResponse>() {
                @Override
                public void onSuccess(TestProto.TestResponse testResponse) {
                    System.out.println("服务器端成功响应回来了");
                    System.out.println(testResponse.getResult());
                }

                @Override
                public void onFailure(Throwable throwable) {
                    System.out.println("服务器端响应时出现异常了");
                }
            }, Executors.newCachedThreadPool());


            managedChannel.awaitTermination(5000,TimeUnit.SECONDS);
        }catch (Exception e){

        }finally {
            managedChannel.shutdown();
        }
    }
}
